package net.nettytlv;

import net.nettytlv.codec.Encoder;
import net.nettytlv.codec.ObjectDecoder;

import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TlvClient {

    private final static Bootstrap bootstrap = new Bootstrap();

    private static TlvClient ourInstance = new TlvClient();

    public static TlvClient getInstance() {
        return ourInstance;
    }

    private TlvClient() {
    }

    public static void main(String[] args) {
        bootstrap
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .remoteAddress("127.0.0.1", 9090)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline()
                                .addLast(new IdleStateHandler(0, 10, 0, TimeUnit.SECONDS))
                                .addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 1, 2))
                                .addLast(new ObjectDecoder())
                                .addLast(new Encoder())
                                .addLast(new ConnectChannelHandler())
                                .addLast(new PacketChannelHandler())
                        ;
                    }
                })
                .option(ChannelOption.SO_KEEPALIVE, true);
        TlvClient.getInstance().connect();
    }

    public synchronized void connect() {
        log.info("connect...");
        bootstrap.connect().addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                return;
            }

            future.channel().eventLoop().schedule(() -> connect(), 5, TimeUnit.SECONDS);
        });
    }
}
